package com.etung.iot.demo.configs;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.Map;


@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer {
        /**
         * 访问根路径改成跳转 index.html页面 （简化部署方案： 可以把前端打包直接放到项目的 webapp，上面的配置）
         */
        @Override
        public void addViewControllers(ViewControllerRegistry registry) {
            registry.addViewController("/").setViewName("index.html");
        }

//        @Override
//        public void addResourceHandlers(ResourceHandlerRegistry registry) {
//
//            registry.addResourceHandler("/webjars/**")
//                            .addResourceLocations("classpath:/META-INF/resources/webjars/");
//
//
//
//        }

        @Bean
        public CorsFilter corsFilter() {
            final UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
            final CorsConfiguration corsConfiguration = new CorsConfiguration();
            //是否允许请求带有验证信息
            corsConfiguration.setAllowCredentials(true);
            // 允许访问的客户端域名
            corsConfiguration.addAllowedOrigin("*");
            // 允许服务端访问的客户端请求头
            corsConfiguration.addAllowedHeader("*");
            // 允许访问的方法名,GET POST等
            corsConfiguration.addAllowedMethod("*");
            urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
            return new CorsFilter(urlBasedCorsConfigurationSource);
        }
}
